/*
 * SSH Assistant - Helper for SSH key, agent, and tunnel management.
 *
 * Copyright (c) 2007 Dave Smith <dizzyd@dizzyd.com>
 * Copyright (c) 2005-2006 Justin Mecham <justin@aspect.net>
 * Copyright (c) 2003 Michael K Link <mlink@synthemesc.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#import "SSHAssistantPreferencePane.h"

@implementation SSHAssistantPreferencePane

- (void) mainViewDidLoad
{
	// Load Preferences
	[self loadPreferences];
}

/**
* Preference Pane Deselection
*
* Save any pending preference and data changes before the preference pane
* deselects.
*/
- (void) willUnselect
{
	// Save Preferences
	[self savePreferences];

	// Save Managed Objects
    [[self managedObjectContext] save:nil];
}

/**
* Load Preferences
*/
- (void) loadPreferences
{
	defaults    = [NSUserDefaults standardUserDefaults];
	preferences = [[NSMutableDictionary alloc] init];

    [preferences addEntriesFromDictionary:[defaults persistentDomainForName:[[NSBundle bundleForClass:[self class]] bundleIdentifier]]];

	[enableSSHAssistantCheckbox setState:[[preferences objectForKey:@"enableSSHAssistant"] boolValue]];
}

/**
* Save Preferences
*/
- (void) savePreferences
{
	[preferences setObject:[NSNumber numberWithBool:[enableSSHAssistantCheckbox state]] forKey:@"enableSSHAssistant"];
	[defaults setPersistentDomain:preferences forName:[[NSBundle bundleForClass:[self class]] bundleIdentifier]];
}

/**
* Add Default Identity
*
* TODO Load the actual default identity instead of using this <default-ssh-key> crap...
*/
- (IBAction) addDefaultIdentity:(id)sender
{
	NSManagedObject * identity = [NSEntityDescription insertNewObjectForEntityForName:@"Identity" inManagedObjectContext:managedObjectContext];
	[identity setValue:@"<default-ssh-key>" forKey:@"path"];
    [identitiesTable reloadData];
}

/**
* Add Identity
*
* Displays an Open dialog, allowing the user to select an identity (an SSH private
* key) for management by SSH Assistant.
*/
- (IBAction) addIdentity:(id)sender
{

	NSString    * openPath  = [[[NSString alloc] initWithFormat:@"%@/.ssh", NSHomeDirectory()] autorelease];
	NSOpenPanel * openPanel = [NSOpenPanel openPanel];
	
	[openPanel setAllowsMultipleSelection:NO];
	[openPanel setCanChooseFiles:YES];
	[openPanel setCanChooseDirectories:NO];

	[openPanel beginSheetForDirectory:openPath
								 file:@"id_dsa"
								types:nil
					   modalForWindow:[[self mainView] window]
					    modalDelegate:self
					   didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
					      contextInfo:NULL];

}

/**
* Callback for Adding Identities
*/
- (void) openPanelDidEnd:(NSOpenPanel *)sheet
              returnCode:(int)returnCode
             contextInfo:(void *)contextInfo
{
	if (returnCode == NSOKButton)
	{
		NSManagedObject * identity = [NSEntityDescription insertNewObjectForEntityForName:@"Identity" inManagedObjectContext:managedObjectContext];
		[identity setValue:[sheet filename] forKey:@"path"];
    }
}

/**
* Application Support Folder
*
* Returns the support folder for the application, used to store the CoreData
* data file.
*/
- (NSString *) applicationSupportFolder
{
    NSArray  * paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString * basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
    return [basePath stringByAppendingPathComponent:@"sshAssistant"];
}

/**
* Managed Object Model
*
* Creates, retains, and returns the managed object model for the application 
* by merging all of the models found in the application bundle and all of the 
* framework bundles.
*/
- (NSManagedObjectModel *) managedObjectModel
{
    if (managedObjectModel != nil)
	{
        return managedObjectModel;
    }
    NSMutableSet * allBundles = [[NSMutableSet alloc] init];
    [allBundles addObject:[NSBundle mainBundle]];
    [allBundles addObjectsFromArray:[NSBundle allFrameworks]];
	[allBundles addObject:[NSBundle bundleForClass:[self class]]];

    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:[allBundles allObjects]] retain];
    [allBundles release];

    return managedObjectModel;
}

/**
* Persistent Store Coordinator
*
* Returns the persistent store coordinator for the application.  This 
* implementation will create and return a coordinator, having added the 
* store for the application to it.  (The folder for the store is created, 
* if necessary.)
*/
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator
{

    if (persistentStoreCoordinator != nil)
        return persistentStoreCoordinator;

    NSFileManager * fileManager;
    NSString      * applicationSupportFolder = nil;
    NSURL         * url;
    NSError       * error;
    
    fileManager = [NSFileManager defaultManager];
    applicationSupportFolder = [self applicationSupportFolder];

    if (![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL])
        [fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil];
    
    url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent:@"sshAssistant.xml"]];
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error])
        [[NSApplication sharedApplication] presentError:error];

    return persistentStoreCoordinator;

}

/**
* Managed Object Context
*
* Returns the managed object context for the application (which is already
* bound to the persistent store coordinator for the application.) 
*/
- (NSManagedObjectContext *) managedObjectContext
{

    if (managedObjectContext != nil)
        return managedObjectContext;

    NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
	{
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    
    return managedObjectContext;

}

/**
* Deallocation Callback
*/
- (void) dealloc
{
    
	// Preferences
	[defaults release], defaults = nil;
	[preferences release], preferences = nil;
    
	// CoreData
    [managedObjectContext release], managedObjectContext = nil;
    [persistentStoreCoordinator release], persistentStoreCoordinator = nil;
    [managedObjectModel release], managedObjectModel = nil;
    
    [super dealloc];
    
}

@end